package net.fornwall.eclipsecoder.languages;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.Platform;

public class LanguageSupportFactory {

	/**
	 * Create a <code>LanguageSupport</code> instance for the given
	 * programming language.
	 * 
	 * @param languageName
	 *            The name of the programming language.
	 * @return a language support if one is found, or null if no one could be
	 *         found
	 */
	public static LanguageSupport createLanguageSupport(String languageName)
			throws Exception {
		IExtensionRegistry registry = Platform.getExtensionRegistry();
		IExtensionPoint extensionPoint = registry
				.getExtensionPoint(LanguageSupport.EXTENSION_SUPPORT_ID);
		IExtension[] extensions = extensionPoint.getExtensions();

		for (int i = 0; i < extensions.length; i++) {
			IConfigurationElement[] elements = extensions[i]
					.getConfigurationElements();
			String supportedLanguage = elements[0].getAttribute("language");
			if (supportedLanguage.equals(languageName)) {
				LanguageSupport result = (LanguageSupport) elements[0]
						.createExecutableExtension("class");
				return result;
			}
		}

		return null;
	}

	/**
	 * Get all supported languages (where support for a programming language is
	 * given by a plugin).
	 * 
	 * @return a list of all supported languages
	 */
	public static List<String> supportedLanguages() {
		List<String> result = new ArrayList<String>();
		IExtensionRegistry registry = Platform.getExtensionRegistry();
		IExtensionPoint extensionPoint = registry
				.getExtensionPoint(LanguageSupport.EXTENSION_SUPPORT_ID);
		IExtension[] extensions = extensionPoint.getExtensions();
		for (IExtension extension : extensions) {
			IConfigurationElement[] elements = extension
					.getConfigurationElements();
			String supportedLanguage = elements[0].getAttribute("language");
			result.add(supportedLanguage);
		}
		Collections.sort(result);
		return result;
	}

	private LanguageSupportFactory() {
		// never called - only static methods are used
	}
}
